package org.wu.framework.core.io;

import org.wu.framework.core.exception.AssertFactory;
import org.wu.framework.core.utils.ClassUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;


public class ClassPathScriptResource implements ScriptResource {


    private final String path;


    private final ClassLoader classLoader;

    private final Class<?> clazz;


    /**
     * Create a new {@code ClassPathScriptResource} for {@code ClassLoader} usage.
     * <p>A leading slash will be removed, as the {@code ClassLoader} resource
     * access methods will not accept it.
     * <p>The default class loader will be used for loading the resource.
     *
     * @param path the absolute path within the class path
     * @see ClassUtils#getDefaultClassLoader()
     */
    public ClassPathScriptResource(String path) {
        this(path, (ClassLoader) null);
    }

    public ClassPathScriptResource(String path, ClassLoader classLoader) {
        AssertFactory.notNull(path, "Path must not be null");
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        this.path = path;
        this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
        this.clazz = null;
    }

    /**
     * 脚本名称
     *
     * @return 脚本名称
     */
    @Override
    public String getPath() {
        return path;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        InputStream is;
        if (this.clazz != null) {
            is = this.clazz.getResourceAsStream(this.path);
        } else if (this.classLoader != null) {
            is = this.classLoader.getResourceAsStream(this.path);
        } else {
            is = ClassLoader.getSystemResourceAsStream(this.path);
        }
        if (is == null) {
            throw new FileNotFoundException(" cannot be opened because it does not exist");
        }
        return is;
    }
}
